import Menu from "antd/lib/menu"
import { ipcRenderer } from "electron"
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"
import path from "path"
import Skeleton from "antd/lib/skeleton"
import Tabs from "antd/lib/tabs"
import Layout from "antd/lib/layout"
import Sider from "antd/lib/layout/Sider"
import Tag from "antd/lib/tag"
import Card from "antd/lib/card"
import Result from "antd/lib/result"
import Modal from "antd/lib/modal"
import FileContent, { FileContentRef } from "./FileContent"
import { ExclamationCircleOutlined } from "@ant-design/icons"
import { useAsyncListener } from "./utils/Hooks"
const option = {
  lg: "zh-CN",
}
const { TabPane } = Tabs
const { confirm } = Modal
// import JSONEditorReact from

interface Props {
  nowData: string
  assetUrl: string
  dataUrl: string
}

interface DataRoute {
  assetUrl: string
  dataUrl: string
  dict: string[]
}

export enum FileMotion {
  idle,
  save,
  load,
}

interface AbortFlag {
  abort: (reason?: any) => void
}

const preloadRoute = async (assetUrl = "", dataUrl = "") => {
  // 如果有数据存 localStorage，如果没有数据，从 localStorage 读取
  if (assetUrl && dataUrl) {
    window.localStorage.setItem("assetUrl", assetUrl)
    window.localStorage.setItem("dataUrl", dataUrl)
  } else {
    assetUrl = window.localStorage.getItem("assetUrl")!
    dataUrl = window.localStorage.getItem("dataUrl")!
  }
  // 读取字典
  if (assetUrl && dataUrl) {
    const dict = await ipcRenderer.invoke("readdir", dataUrl)
    return {
      assetUrl,
      dataUrl,
      dict,
    }
  } else {
    return undefined
  }
}

const urlListener = (event: any = null, assetUrl = "", dataUrl = "") => {
  return preloadRoute(assetUrl, dataUrl)
}

const DataEditor = () => {
  const [curFile, setCurFile] = useState("")

  const { error, result, loading } = useAsyncListener(
    (listener) => {
      ipcRenderer.on("route-change", listener)
    },
    (listener) => {
      ipcRenderer.off("route-change", listener)
    },
    urlListener,
    [],
    true,
    []
  )

  const contentRef = useRef<FileContentRef>(null)
  const { changed = false } = contentRef.current || {}

  const handleSelectFile = useCallback(
    async (event: any) => {
      const { key } = event
      if (changed) {
        confirm({
          title: "确定要切换文件吗？",
          icon: <ExclamationCircleOutlined />,
          content: "如果切换文件，未保存的修改将会丢失",
          okText: "确定",
          cancelText: "取消",
          onOk() {
            setCurFile(key)
            console.log("文件选择")
          },
          onCancel() {
            console.log("Cancel")
          },
        })
      } else {
        setCurFile(key)
        console.log("文件选择")
      }
    },
    [contentRef]
  )

  const handleRightClick = useCallback((type = 0, param = "") => {
    return () => {
      console.log("待补充右键事件")
    }
  }, [])

  if (result) {
    const { assetUrl, dataUrl, dict } = result

    const jsonDict = dict
      .filter((name: string) => {
        return name.endsWith(".json") && !name.startsWith("$schema.")
      })
      .map((name: string) => {
        return name.substring(0, name.lastIndexOf("."))
      })

    const assets = jsonDict.map((value: string, i: any) => {
      return (
        <Menu.Item key={value} onContextMenu={handleRightClick(0, value)}>
          {value}
        </Menu.Item>
      )
    })
    const aside = (
      <Sider>
        <Layout
          style={{
            display: "flex",
            flexDirection: "column",
            alignItems: "stretch",
            height: "100%",
          }}
        >
          <Card
            size="small"
            title={
              <>
                {path.basename(assetUrl)}
                <Tag color="green">npm</Tag>
              </>
            }
          >
            数据路径：{path.relative(assetUrl, dataUrl)}
          </Card>
          <Layout style={{ flex: 1 }}>
            <Menu
              onClick={handleSelectFile}
              onContextMenu={handleRightClick(0)}
              style={{ overflowY: "auto", height: "100%" }}
              theme="dark"
            >
              {assets}
            </Menu>
          </Layout>
          <div>新建</div>
        </Layout>
      </Sider>
    )

    if (curFile) {
      return (
        <Layout>
          {aside}
          <FileContent
            route={dataUrl}
            name={curFile}
            ref={contentRef}
            curFile={curFile}
            setCurFile={setCurFile}
          />
        </Layout>
      )
    } else if (dict.length === 0) {
      return (
        <Result
          title="项目列表为空"
          subTitle="当前配置目录无数据文件，请从左侧选择新建"
          style={{ width: "100%" }}
        />
      )
    } else if (loading) {
      return <Skeleton active />
    } else {
      return (
        <Layout>
          {aside}
          <Result
            title="项目未选择"
            subTitle="请从左侧菜单选择项目配置"
            style={{ width: "100%", height: "100%" }}
          />
        </Layout>
      )
    }
  } else {
    return (
      <Result
        title="未配置项目目录"
        subTitle="请先正确配置项目目录以及数据目录"
      />
    )
  }
}

export default DataEditor
